// customize 二次封装
import axios from "axios";
import querystring from "querystring";
import {ElMessage} from "element-plus";
import {useUserStore} from "@/stores/user.js";

const instance = axios.create({
    baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
    timeout: 5000
})
// 拦截器最常用
// 发送数据之前
instance.interceptors.request.use(
    config=> {
        const userStore = useUserStore()
        const token = userStore.userInfo.token
        if (token) {
            config.headers.Authorization = `Bearer ${token}`
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)
// 获取数据之前
instance.interceptors.response.use(
    // 网络请求成功,不管是否是前端错误还是后端错误
    resp=> {
        console.log("resp")
        console.log(resp.data)
        return resp.status === 200? Promise.resolve(resp.data): Promise.reject(resp)
    },
    error => {
        // 发送过程有错
        const {response} = error
        console.log(response)
        errorHandle(response.status, response.data.message)
    }
)

const errorHandle = (status, info)=> {
    let msg = ''
    switch (status) {
        case 400:
            msg = '语义有误'
            console.log("语义有误")
            break;
        case 401:
            msg = 'token过期服务器认证失败'
            console.log("token过期服务器认证失败")
            break;
        case 403:
            msg = '无权访问服务器拒绝访问'
            console.log("无权访问服务器拒绝访问")
            break;
        case 404:
            msg = '地址错误'
            console.log("地址错误")
            break;
        case 500:
            msg = '服务器遇到意外'
            console.log("服务器遇到意外")
            break;
        case 502:
            msg = '服务器无响应'
            console.log("服务器无响应")
            break;
        default:
            msg = info
            console.log(info);
            break;
    }
    // 提示错误信息
    ElMessage({
        type: "error",
        message: msg,
        duration: 2000
    })
}

const defaultFailure = (message, code, url)=> {
    console.warn(`请求地址：${url}, 状态码: ${code}, 信息：${message}`)
    ElMessage.warning(message)
}
const defaultError = (err)=> {
    console.error(err)
    ElMessage.error('发生了一些错误，请联系管理员')
}


export default instance
